<html>
<head>

<title>Groovy Goodness: Setting Date and Calendar Values with Subscript Operators</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Setting Date and Calendar Values with Subscript Operators</h3>

<div class="post">
<p>In Groovy 1.7.3 we have some new ways to set the value of <code>Date</code> or <code>Calendar</code> objects. We can for example use the subscript operators (<code>getAt()</code> and <code>putAt()</code> methods) to define value for fields or get the value from a field. The fields are the <code>Calendar</code> constants like <code>Calendar.YEAR</code>, <code>Calendar.DATE</code>.</p>
<pre class="brush:groovy">
import static java.util.Calendar.*

def date = new Date()
// Set value with subscript operator
date[YEAR] = 2010
date[MONTH] = JUNE
date[DATE] = 14

assert 110 == date.year
assert 5 == date.month
assert 14 == date.date

// Get value with subscript operator
assert 2010 == date[YEAR]  
assert JUNE == date[MONTH]
assert 14 == date[DATE]


def cal = Calendar.instance
// Set value with subscript operator
cal[YEAR] = 2000
cal[MONTH] = DECEMBER
cal[DATE] = 25

assert '2000-12-25' == cal.format('yyyy-MM-dd')
assert 2000 == cal[YEAR]  // Get value with subscript operator
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>